"""
verify that copied agent preserves configuration from source agent
test configuration preservation after adding knowledge base
"""
import sys
from pathlib import Path

# Add project root to Python path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

import logging
from src.llm.hiagent_app.services.agent_knowledge_service import AgentKnowledgeService
from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
from src.llm.hiagent_app.config.hiagent_config import HiAgentConfig

# configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def get_agent_config(api_client, agent_id, workspace_id):
    """get agent configuration"""
    try:
        body = {
            "WorkspaceID": workspace_id,
            "AppID": agent_id
        }
        response = api_client.make_request("GetAppConfigDraft", body)
        return response.get("AppConfigDraft", {})
    except Exception as e:
        logger.error(f"Failed to get agent config: {str(e)}")
        return None


def compare_configs(source_config, new_config):
    """compare source and new agent configurations"""
    logger.info("\n" + "=" * 60)
    logger.info("Configuration Comparison")
    logger.info("=" * 60)

    if not source_config:
        logger.warning("Source config is empty, cannot compare")
        return False

    if not new_config:
        logger.error("New config is empty")
        return False

    # Check important fields that should be preserved
    fields_to_check = [
        "ModelID",
        "PrePrompt"
    ]

    model_config_fields = [
        "Temperature",
        "TopP",
        "MaxTokens",
        "Strategy"
    ]

    preserved = True

    # Check top-level fields
    for field in fields_to_check:
        source_value = source_config.get(field)
        new_value = new_config.get(field)

        if source_value is not None:
            if source_value == new_value:
                logger.info(f"✓ {field}: Preserved (Value: {source_value})")
            else:
                logger.warning(f"✗ {field}: Changed")
                logger.warning(f"  Source: {source_value}")
                logger.warning(f"  New: {new_value}")
                # PrePrompt might be intentionally changed
                if field != "PrePrompt":
                    preserved = False

    # Check ModelConfig fields
    source_model_config = source_config.get("ModelConfig", {})
    new_model_config = new_config.get("ModelConfig", {})

    logger.info("\nModelConfig comparison:")
    for field in model_config_fields:
        source_value = source_model_config.get(field)
        new_value = new_model_config.get(field)

        if source_value is not None:
            if source_value == new_value:
                logger.info(f"✓ {field}: Preserved (Value: {source_value})")
            else:
                logger.warning(f"✗ {field}: Changed")
                logger.warning(f"  Source: {source_value}")
                logger.warning(f"  New: {new_value}")
                preserved = False

    # Check that knowledge base was added
    logger.info("\nKnowledge base configuration:")
    knowledge_ids = new_config.get("KnowledgeIDs", [])
    knowledge_config = new_config.get("KnowledgeConfig", {})

    if knowledge_ids:
        logger.info(f"✓ KnowledgeIDs added: {knowledge_ids}")
    else:
        logger.error("✗ KnowledgeIDs not found")
        preserved = False

    if knowledge_config:
        logger.info(f"✓ KnowledgeConfig added: {knowledge_config}")
    else:
        logger.error("✗ KnowledgeConfig not found")
        preserved = False

    # Check RAG is enabled
    if new_model_config.get("RagEnabled"):
        logger.info("✓ RagEnabled is True")
    else:
        logger.error("✗ RagEnabled is not True")
        preserved = False

    return preserved


def test_configuration_preservation():
    """test that configuration is preserved from source agent"""
    logger.info("=" * 60)
    logger.info("Test: Configuration Preservation")
    logger.info("=" * 60)

    api_client = HiAgentAPIClient()
    service = AgentKnowledgeService()
    workspace_id = HiAgentConfig.DEFAULT_WORKSPACE_ID
    source_agent_id = "d3tjsrvi96maquv5k8v0"

    logger.info(f"Source Agent ID: {source_agent_id}")
    logger.info(f"Workspace ID: {workspace_id}")

    # Step 1: Get source agent configuration
    logger.info("\nStep 1: Getting source agent configuration...")
    source_config = get_agent_config(api_client, source_agent_id, workspace_id)

    if not source_config:
        logger.error("Failed to get source agent configuration")
        return False

    logger.info("Source agent configuration retrieved successfully")
    logger.info(f"Source ModelID: {source_config.get('ModelID')}")
    logger.info(f"Source PrePrompt: {source_config.get('PrePrompt', 'N/A')[:100]}...")

    # Step 2: Create new agent by copying
    logger.info("\nStep 2: Creating new agent by copying from source...")

    try:
        agent_id, knowledge_id = service.create_agent_with_knowledge(
            agent_name="test_config_preserve",
            knowledge_name="test_knowledge_preserve",
            agent_description="test configuration preservation",
            workspace_id=workspace_id,
            source_agent_id=source_agent_id
        )
        logger.info(f"Agent created successfully - ID: {agent_id}, Knowledge ID: {knowledge_id}")
    except Exception as e:
        logger.error(f"Failed to create agent: {str(e)}")
        return False

    # Step 3: Get new agent configuration
    logger.info("\nStep 3: Getting new agent configuration...")
    new_config = get_agent_config(api_client, agent_id, workspace_id)

    if not new_config:
        logger.error("Failed to get new agent configuration")
        # Cleanup
        service._cleanup_resources(agent_id, knowledge_id, workspace_id)
        return False

    logger.info("New agent configuration retrieved successfully")
    logger.info(f"New ModelID: {new_config.get('ModelID')}")
    logger.info(f"New PrePrompt: {new_config.get('PrePrompt', 'N/A')[:100]}...")

    # Step 4: Compare configurations
    logger.info("\nStep 4: Comparing configurations...")
    preserved = compare_configs(source_config, new_config)

    # Cleanup
    logger.info("\nCleaning up test resources...")
    service._cleanup_resources(agent_id, knowledge_id, workspace_id)

    return preserved


def main():
    """main test function"""
    logger.info("Starting configuration preservation verification")
    logger.info("=" * 60)

    result = test_configuration_preservation()

    logger.info("\n" + "=" * 60)
    logger.info("Test Result")
    logger.info("=" * 60)

    if result:
        logger.info("✓ TEST PASSED")
        logger.info("Configuration from source agent was preserved")
        logger.info("Knowledge base configuration was added successfully")
    else:
        logger.error("✗ TEST FAILED")
        logger.error("Configuration was not properly preserved")
        logger.error("Please check the comparison details above")


if __name__ == "__main__":
    main()
